import config from './config.js';
import md5 from 'js-md5';
import storage from '@/storage/storage.js';

const requestTypeArr = ['GET', 'POST', 'PUT', 'DELETE'];

// 尝试请求
const request = ({
	requestType,
	method,
	sendmsg,
	isLoaing
}) => {
	return new Promise((resolve, reject) => {
		let palt = uni.getStorageSync('yw_platform');
		let imei = uni.getStorageSync('appimei'); //手机IMEI
		if (null == palt || "" == palt || null == imei || "" == imei) { // 若无手机信息
			//获取手机的信息
			uni.getSystemInfo({
				success: function(res) {
					if ('ios' == res.platform) {
						uni.setStorageSync('yw_platform', '1');
					} else if ('android' == res.platform) {
						uni.setStorageSync('yw_platform', '2');
					} else {
						uni.setStorageSync('yw_platform', '2');
					}
					//  设置IMEI 
					uni.setStorageSync('appimei', '1234567890');
					// 开始通信
					begincommin({
						requestType,
						method,
						sendmsg,
						isLoaing
					}).then(res => {
						resolve(res)
					}).catch(err => {
						reject(err);
					});
				},
			})
		} else { // 若有手机信息
			// 开始通信
			begincommin({
				requestType,
				method,
				sendmsg,
				isLoaing
			}).then(res => {
				resolve(res)
			}).catch(err => {
				reject(err);
			});
		}
	}).then(res => [null, res]).catch(err => [err])
}

// 开始通信
const begincommin = ({
	requestType,
	method,
	sendmsg,
	isLoaing
}) => {
	return new Promise((resolve, reject) => {
		// 获取时间
		let timestamp = (Date.parse(new Date())) / 1000;
		let request_type = requestType.toUpperCase();
		if ("" == sendmsg || null == sendmsg) {
			sendmsg = "{}";
		}
		// 判断是否可用的四个请求类型
		if (requestTypeArr.indexOf(request_type) == -1) {
			throw `确认请求类型-->${request_type}`
		}
		// 请求header-content-type
		let headerContentType = "application/x-www-form-urlencoded;charset=UTF-8";
		if (request_type == "PUT") {
			let headerContentType = "application/json;charset=UTF-8";
		}
		// 生成签名
		CalcuMD5(sendmsg).then(res => {
			//参数拷贝
			let data = '';
			if (Object.prototype.toString.call(sendmsg) == '[object Object]') {
				data = Object.assign({}, sendmsg);
			}
			if (config.global_isTest) {
				console.log('method==>' + method, data);
			}
			// 请求地址
			let requestUrl;
			if (config.ApiVersion) {
				requestUrl = `${config.global_baseddConnUrl}/${config.ApiVersion}/${method}`
			} else {
				requestUrl = `${config.global_baseddConnUrl}/${method}`
			}
			if (isLoaing) {
				uni.showLoading({
					title: ''
				});
			}
			uni.request({
				url: requestUrl, //仅为示例，并非真实接口地址。
				method: request_type,
				data: data,
				header: {
					'X-Requested-With': 'XMLHttpRequest',
					'content-type': headerContentType, //自定义请求头信息
					'Yw-Sign': res,
					'Yw-Time': timestamp,
					'Authorization': 'Bearer ' + storage.get('token'),
					'version': config.global_version,
					'plat': uni.getStorageSync('yw_platform'),
					'sign': uni.getStorageSync('appimei'),
				},
				success: (data) => {
					if (isLoaing) {
						uni.hideLoading()
					}
					//定义变量
					let jsondata = data;
					// 打印
					if (config.global_isTest) {
						console.log(jsondata)
					}
					//返回状态：200 返回成功，401：重新登录，422：后端返回报错，500，请求异常
					switch (parseInt(jsondata.statusCode)) {
						case 200:
							resolve(jsondata.data)
							break;
						case 401:
							console.log("重新登录")
							uni.removeStorage({
								key: 'yw_token'
							});
							setTimeout(() => {
								uni.reLaunch({
									url: '/pages/login/login'
								})
							}, 300)
							reject(jsondata.data)
							break;
						case 422:
							console.error(jsondata.data.message)
							uni.showToast({
								title: jsondata.data.message,
								icon: 'none'
							})
							reject(jsondata.data)
							break;
						case 500:
							console.error(jsondata.data.message)
							uni.showToast({
								title: jsondata.data.message,
								icon: 'none'
							})
							reject(jsondata.data)
							break;
						default:
							console.error(jsondata.data.message)
							uni.showToast({
								title: jsondata.data.message,
								icon: 'none'
							})
							reject(jsondata.data)
					}
				},
				fail: (err) => {
					if (isLoaing) {
						uni.hideLoading()
					}
					console.log(`失败原因==>`, err)
					reject(err);
				}
			})
		});
	})
}

// md5加密请求体
function CalcuMD5(obj) {
	return new Promise(resolve => {
		// 如果不是对象  也就是说使用的GET和DELETE请求 那么不用加密  直接返回空
		const key = config.global_aeskey;
		let sign = ''
		if (Object.prototype.toString.call(obj) != '[object Object]') {
			sign = key + '--' + key
		} else {
			if (JSON.stringify(obj) === '{}') {
				sign = key + '--' + key
			} else {
				Object.keys(obj).sort().forEach((k) => {
					sign += key + k + '--' + obj[k] + key
				})
			}
		}
		resolve(md5(sign).toUpperCase());
	})
}

export default request
